 package com.szy.news.activity;
/**
 * @author 辛晓博
 *登录（第三方） 
 * 亮度调节
 * 反馈
 * 搜索
 * 卸载
 * 缓存清除
 * 关于
 * */
import java.util.HashMap;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;
import net.tsz.afinal.http.AjaxParams;

import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Text;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.framework.utils.UIHandler;
import cn.sharesdk.renren.Renren;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.weibo.TencentWeibo;

import com.google.gson.Gson;
import com.szy.news.control.LightnessControl;
import com.szy.news.control.MyApplication;
import com.szy.news.control.UserSetting;
import com.szy.news.update.UpdateVer;
import com.szy.news.util.JsonUtils;
import com.szy.news.util.URL;
import com.szy.news.weather.WeatherActivity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.provider.Settings.System;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Toast;

public class SetActivity extends Activity implements OnClickListener, PlatformActionListener, Callback{
	
	private ImageButton btn_back;
	private int sys_brightness;
	private SeekBar seekBar;
	private ImageButton btn_sina;
	private ImageButton btn_tencent;
	private ImageButton btn_renren;
	private LinearLayout about;
	private LinearLayout feedback;
	private LinearLayout delete;
	private LinearLayout more;
	private LinearLayout weather;
//	private Button btn_update;
	private LinearLayout btn_exit;
	private LinearLayout btn_replace;
	private ImageButton search;
	private Platform platform;
	private int LOGIN_TYPE;
	private static final String urlApk = "http://192.168.137.1:8080/web/RuoshuiNews.apk"; 
	private static final String urlVer = "http://192.168.137.1:8080/web/ver_apk.xml"; 
	private String WEIBO_NAME = "name";
	private static final int MSG_TOAST = 1;
	private static final int MSG_ACTION_CCALLBACK = 2;
	private static final int MSG_CANCEL_NOTIFY = 3;
	/**
	 * SharedPreferences是Android中最容易理解的数据存储技术，
	 * 实际上SharedPreferences处理的就是一个key-value（键值对）,
	 * SharedPreferences常用来存储一些轻量级的数据
	 * */
	private SharedPreferences mySharedPreferences;//定义SharedPreferences
	private int brightness;
	private ContentResolver cResolver;
	private Window window;

	public MyApplication my;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_set);
		
		//初始化sdk
		ShareSDK.initSDK(this);
		
		//实例化SharedPreferences
		mySharedPreferences = getSharedPreferences("mySharedPreferences", MODE_PRIVATE);
		
		
		//实现返回主界面
		btn_back = (ImageButton) findViewById(R.id.back);
		btn_back.setOnClickListener(this);
		//三个外接接口
		btn_sina = (ImageButton) findViewById(R.id.sina);
		btn_sina.setOnClickListener(this);
		btn_tencent = (ImageButton) findViewById(R.id.tencent);
		btn_tencent.setOnClickListener(this);
		btn_renren = (ImageButton) findViewById(R.id.renren);
		btn_renren.setOnClickListener(this);
		//退出软件
		btn_exit = (LinearLayout) findViewById(R.id.btn_exit);
		btn_exit.setOnClickListener(this);
		//退出当前用户
		btn_replace = (LinearLayout) findViewById(R.id.btn_replace);
		btn_replace.setOnClickListener(this);
		//关于
		about = (LinearLayout) findViewById(R.id.about);
		about.setOnClickListener(this);
		//意见反馈
		feedback = (LinearLayout) findViewById(R.id.feedback);
		feedback.setOnClickListener(this);
		//卸载
		delete = (LinearLayout) findViewById(R.id.delete);
		delete.setOnClickListener(this);
		//检查更新
//		btn_update = (Button) findViewById(R.id.update);
//		btn_update.setOnClickListener(this);
		//search搜索
		search = (ImageButton) findViewById(R.id.search);
		search.setOnClickListener(this);
		//更多
		more = (LinearLayout)findViewById(R.id.more);
		more.setOnClickListener(this);
		//天气定位
		weather = (LinearLayout) findViewById(R.id.weather);
		weather.setOnClickListener(this);
		
		my = (MyApplication) this.getApplication();
		
		
		/**
		 * 亮度调节
		 * */
		//定义滑动条
//		seekBar = (SeekBar) findViewById(R.id.sb_brightness);
		//判断自动调节亮度是否开启
//		boolean isAuto = new LightnessControl().isAutoBrightness(SetActivity.this);
		//如果开启则关闭
//		if (isAuto) {
//			seekBar.setEnabled(false);
//		}
//		int bringhtsize = mySharedPreferences.getInt("setting_brightness", 100);
//		Log.e(SetActivity.ACTIVITY_SERVICE, Integer.toString(bringhtsize));
//		seekBar.setProgress(bringhtsize);
//		UserSetting.setLightness(bringhtsize);
//		
//		设置监听事件
//		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
//			@Override
//			public void onStopTrackingTouch(SeekBar seekBar) {
//				Editor editor = mySharedPreferences.edit();
//				editor.putInt("setting_brightness", brightness);
//				editor.commit();
//				
//			}
//			
//			@Override
//			public void onStartTrackingTouch(SeekBar seekBar) {
//				
//			}
//			
//			@Override
//			public void onProgressChanged(SeekBar seekBar, int progress,
//					boolean fromUser) {
//				brightness = progress + 35;
//				new LightnessControl().SetLightness(SetActivity.this, brightness);
//				
//			}
//		});
		
		
		
		//亮度调节
		seekBar = (SeekBar) findViewById(R.id.sb_brightness);
		cResolver = getContentResolver();
		window = getWindow();
//		设置亮度最大值
		seekBar.setMax(255);
//		设置拖动精度每次增加1
		seekBar.setKeyProgressIncrement(1);
		//获取当前的系统亮度
		try {
			brightness = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS);
			sys_brightness = brightness;
		} catch (SettingNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		//将系统亮度设置在进度条上显示
		seekBar.setProgress(brightness);
		//设置滑动条滑动的监听事件
		seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				//设置亮度最小值
				int tmpInt = seekBar.getProgress();
				if (tmpInt<=20) {
					tmpInt=20;
				}
				//根据当前进度调节亮度
				Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, tmpInt);
				tmpInt = Settings.System.getInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, -1);
				WindowManager.LayoutParams wl = getWindow().getAttributes();
				Float tmpFloat = (float) (tmpInt/255);
				if (tmpFloat>0&&tmpFloat<=1) {
					wl.screenBrightness=tmpFloat;
				}
				getWindow().setAttributes(wl);
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				
			}
		});
		
		
		
		
		
		
	}
	
	@Override
	protected void onDestroy() {
		ShareSDK.stopSDK(this);
		super.onDestroy();
	}
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		final Intent intent;
		if (id == R.id.sina) {
			LOGIN_TYPE = 1;
			SinaWeibo sina = new SinaWeibo(SetActivity.this);
			sina.SSOSetting(true);
			sina.setPlatformActionListener(SetActivity.this);
			sina.showUser(null);
			
//			intent = new Intent();
//			intent.setData(Uri.parse("http://d.weibo.com/"));
//			intent.setAction(Intent.ACTION_VIEW);
//			startActivity(intent);
		}else if (id == R.id.tencent) {
			LOGIN_TYPE = 2;
			TencentWeibo tencent = new TencentWeibo(SetActivity.this);
			tencent.SSOSetting(true);
			tencent.setPlatformActionListener(SetActivity.this);
			tencent.showUser(null);
			
//			intent = new Intent();
//			intent.setData(Uri.parse("http://t.qq.com/"));
//			intent.setAction(Intent.ACTION_VIEW);
//			startActivity(intent);
		}else if (id == R.id.renren) {
			LOGIN_TYPE = 3;
			Renren renren = new Renren(SetActivity.this);
			renren.SSOSetting(true);
			renren.setPlatformActionListener(SetActivity.this);
			renren.showUser(null);
			
//			intent = new Intent();
//			intent.setData(Uri.parse("http://share.renren.com/"));
//			intent.setAction(Intent.ACTION_VIEW);
//			startActivity(intent);
		}else if (id == R.id.back) {
			intent = new Intent(SetActivity.this, MainActivity.class);
//			intent.setClass(SetActivity.this, MainActivity.class);
			startActivity(intent);
		}
			else if (id == R.id.btn_replace) {
				MyApplication my=(MyApplication) SetActivity.this.getApplication();
				if(my.isFlag()==false){
					Toast.makeText(SetActivity.this, "当前无用户登录", Toast.LENGTH_SHORT).show();
				}else{
				
				//1/7
					try {
						Toast.makeText(SetActivity.this, "已退出当前用户", Toast.LENGTH_SHORT).show();
						Thread.sleep(1000);						
						FinalHttp fh = new FinalHttp();
						AjaxParams params = new AjaxParams();
						params.put("delete_id", "delete_id");
						params.put("updata", "updata");
						params.put("username", my.getUsername());
						fh.post(URL.login_url, params, new AjaxCallBack<Object>() {
							@Override
							public void onSuccess(Object t) {
								super.onSuccess(t);
							}
						});
						intent = new Intent(SetActivity.this, LoginActivity.class);
			//			MyApplication my=(MyApplication) SetActivity.this.getApplication();
						my.setFlag(false);
			//			intent.setClass(SetActivity.this, MainActivity.class);
						startActivity(intent);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
//					FinalHttp fh = new FinalHttp();
//					AjaxParams params = new AjaxParams();
//					params.put("delete_id", "delete_id");
//					params.put("updata", "updata");
//					params.put("username", my.getUsername());
//					fh.post(URL.login_url, params, new AjaxCallBack<Object>() {
//						@Override
//						public void onSuccess(Object t) {
//							super.onSuccess(t);
//						}
//					});
//					intent = new Intent(SetActivity.this, LoginActivity.class);
//		//			MyApplication my=(MyApplication) SetActivity.this.getApplication();
//					my.setFlag(false);
//		//			intent.setClass(SetActivity.this, MainActivity.class);
//					startActivity(intent);
				}
		}
		else if (id == R.id.about) {
			intent = new Intent(SetActivity.this, AboutActivity.class);
//			intent.setClass(SetActivity.this, AboutActivity.class);
			startActivity(intent);
//			finish();
		}else if (id == R.id.delete){
			//通过程序的包名创建URI 
			Uri packageURI = Uri.parse("package:"+SetActivity.this.getPackageName()); 
			//创建Intent意图 
			intent = new Intent(Intent.ACTION_DELETE,packageURI); 
			//执行卸载程序 
			startActivity(intent);
		}else if(id == R.id.weather){
			intent = new Intent(SetActivity.this,WeatherActivity.class);
			startActivity(intent);
//			finish();
		}else if (id == R.id.update) {
//			Toast.makeText(this, "正在检测版本", Toast.LENGTH_LONG).show(); 
//			UpdateVer uv = new UpdateVer(urlApk,urlVer,SetActivity.this); 
//			uv.checkVer(); 
//			UpdateVer uv = new UpdateVer();
//			uv.onOptionsItemSelected(null);
//			uv.onOptionsItemSelected(item);
		}else if (id == R.id.feedback) {
			intent = new Intent(SetActivity.this, SendActivity.class);
//			intent.setClass(SetActivity.this, SendActivity.class);
			startActivity(intent);
//			finish();
		}else if(id == R.id.more){
			intent = new Intent(SetActivity.this, MyViewPagerActivity.class);
//			intent.setClass(SetActivity.this, MyViewPagerActivity.class);
			startActivity(intent);
//			finish();
		}else if(id == R.id.search){
			intent = new Intent();
			intent.setData(Uri.parse("http://www.baidu.com"));
			intent.setAction(intent.ACTION_VIEW);
			startActivity(intent);
//			finish();
		}else if (id == R.id.btn_exit) {
			intent = new Intent(Intent.ACTION_MAIN);
			intent.addCategory(Intent.CATEGORY_HOME);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			new AlertDialog.Builder(SetActivity.this)
			.setTitle(R.string.option)
			.setIcon(R.drawable.ic_launcher)
			.setMessage(R.string.message)
			.setPositiveButton(R.string.yes, new android.content.DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialoginterface, int i)
    			{
					Settings.System.putInt(cResolver, Settings.System.SCREEN_BRIGHTNESS, sys_brightness);
					startActivity(intent);
					java.lang.System.exit(0);
    				//finish();//只是退出当前activity
    			}
			})
			.setNegativeButton(R.string.no, new android.content.DialogInterface.OnClickListener() {
				
				@Override
				public void onClick(DialogInterface dialog, int which) {
					
				}
			}).show();
		}
	}

	@Override
	public void onCancel(Platform platform, int action) {
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 3;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
	}
	
	
	/**
	 * @author 辛晓博
	 * 授权成功的回调
	 * Platform - 授权平台
	 * action - 操作类型
	 * res - 请求的数据通过res返回
	 * */
	@Override
	public void onComplete(Platform platform, int action, HashMap<String, Object> res) {
		Message msg = new Message();
		
		JsonUtils ju = new JsonUtils();
		String json = ju.fromHashMap(res);
		Gson g = new Gson();
		
		if (LOGIN_TYPE == 1) {
			platform = ShareSDK.getPlatform(this, SinaWeibo.NAME);
		} else if (LOGIN_TYPE == 2) {
			platform = ShareSDK.getPlatform(this, TencentWeibo.NAME);
		} else if (LOGIN_TYPE == 3) {
			platform = ShareSDK.getPlatform(this, Renren.NAME);
		}
		
		try {
			JSONObject obj = new JSONObject(json);
			java.lang.System.out.println(json);
			String names = obj.getString(WEIBO_NAME);
			if (names.equals("")) {
				Toast.makeText(this, "未获取到用户名", Toast.LENGTH_SHORT).show();
			} else {
				my.setUsername(names);
				my.setFlag(true);
			}
			Log.e("name", names);
		} catch (JSONException e) {
			e.printStackTrace();
		}

		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 1;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
		
	}
	
	
	/**
	 * 错误回调
	 * */
	@Override
	public void onError(Platform platform, int action, Throwable t) {
		t.printStackTrace();
		t.getMessage();
		
		Message msg = new Message();
		msg.what = MSG_ACTION_CCALLBACK;
		msg.arg1 = 2;
		msg.arg2 = action;
		msg.obj = platform;
		UIHandler.sendMessage(msg, this);
		
	}

	@Override
	public boolean handleMessage(Message msg) {
		switch (msg.what) {
		case MSG_TOAST:{
			String text = String.valueOf(msg.obj);
			Toast.makeText(SetActivity.this, text, Toast.LENGTH_SHORT).show();
		}
		break;
		case MSG_ACTION_CCALLBACK:{
			switch (msg.arg1) {
			case 1:{//授权成功
				showNotification(2000,"Auth successfully");
				
				switch (LOGIN_TYPE) {
				case 1:
					Platform pf1 = ShareSDK.getPlatform(SetActivity.this, SinaWeibo.NAME);
					Log.e("sharesdk use_id", pf1.getDb().getUserId()); //获取用户id
					Log.e("sharesdk use_name", pf1.getDb().getUserName());//获取用户名称
					Log.e("sharesdk use_icon", pf1.getDb().getUserIcon());//获取用户头像
					break;

				case 2:
					Platform pf2 = ShareSDK.getPlatform(SetActivity.this, SinaWeibo.NAME);
					Log.e("sharesdk use_id", pf2.getDb().getUserId()); //获取用户id
					Log.e("sharesdk use_name", pf2.getDb().getUserName());//获取用户名称
					Log.e("sharesdk use_icon", pf2.getDb().getUserIcon());//获取用户头像
					break;
					
				case 3:
					Platform pf3 = ShareSDK.getPlatform(SetActivity.this, SinaWeibo.NAME);
					Log.e("sharesdk use_id", pf3.getDb().getUserId()); //获取用户id
					Log.e("sharesdk use_name", pf3.getDb().getUserName());//获取用户名称
					Log.e("sharesdk use_icon", pf3.getDb().getUserIcon());//获取用户头像
					break;
				}
			}
				
			break;

			case 2: {//失败
				String expName = msg.obj.getClass().getSimpleName();
				showNotification(2000, "Auth unsuccessfully");
					
			}
			break;
			
			case 3: {//取消
				showNotification(2000, "Cancel authorization");
			} 
			break;
			
			
			}
		}
		break;

		case MSG_CANCEL_NOTIFY: {
			NotificationManager nm = (NotificationManager) msg.obj;
			if (nm != null) {
				nm.cancel(msg.arg1);
			}
		}
		break;
		}
		return false;
	}
	
	//在状态栏提示分享操作
	private void showNotification(long cancelTime, String text) {
		Context app = getApplicationContext();
		NotificationManager nm = (NotificationManager) app.getSystemService(Context.NOTIFICATION_SERVICE);
		final int id = Integer.MAX_VALUE/13+1;
		nm.cancel(id);
		
		long when = java.lang.System.currentTimeMillis();
		Notification notification = new Notification(R.drawable.ic_launcher, text, when);
		PendingIntent pi = PendingIntent.getActivity(app, 0, new Intent(), 0);
		notification.setLatestEventInfo(app, "sharesdk test", text, pi);
		notification.flags = Notification.FLAG_AUTO_CANCEL;
		nm.notify(id, notification);
		
		if (cancelTime > 0) {
			Message msg = new Message();
			msg.what = MSG_CANCEL_NOTIFY;
			msg.obj = nm;
			msg.arg1 = id;
			UIHandler.sendMessageDelayed(msg, cancelTime, this);
		}
	}
}
